package com.maas.util.mybatis.jpa.littlenb.support.template.update;

import com.littlenb.mybatisjpa.support.template.SqlTemplate;
import com.littlenb.mybatisjpa.support.template.UpdateIgnoreNullSqlTemplate;
import com.littlenb.mybatisjpa.util.ColumnMetaResolver;
import com.littlenb.mybatisjpa.util.PersistentUtil;
import com.maas.util.mybatis.jpa.littlenb.common.JpaTools;

import java.lang.reflect.Field;

/**
 * @author sway.li
 **/
public class MyUpdateIgnoreNullSqlTemplate implements SqlTemplate {

  public static final MyUpdateIgnoreNullSqlTemplate INSTANCE = new MyUpdateIgnoreNullSqlTemplate();

  public String updateSet="";
  @Override
  public String parseSQL(Class<?> type) {
    // columns
    StringBuilder sets = new StringBuilder();
    if(JpaTools.isEmpty(updateSet)){
      sets.append("<trim prefix='' suffix='' suffixOverrides=',' > ");
      for (Field field : PersistentUtil.getPersistentFields(type)) {

        sets.append("<if test='" + field.getName() + "!= null'> ");
        // columnName = #{ }

        sets.append(PersistentUtil.getColumnName(field)).append(" = ")
                .append(ColumnMetaResolver.resolveSqlPlaceholder(field)).append(" , ");
        sets.append("</if> ");
      }

      sets.append("</trim> ");
    }else{
      sets.append(updateSet +" ");
    }


    return "UPDATE " + PersistentUtil.getTableName(type) + " set " + sets.toString();
  }

}
